<script setup lang="ts">
import { ref, computed, watch } from "vue";
import ReCol from "@/components/ReCol";
import { batchFormRules } from "./utils/rule";
import {
  BatchFormProps,
  UserOption,
  AgentOption,
  AccountOption,
  BatchAccountItem
} from "./utils/types";
import { Delete } from "@element-plus/icons-vue";
import { hasPerms } from "@/utils/auth";

interface Props extends BatchFormProps {
  userOptions?: UserOption[];
  agentOptions?: AgentOption[];
  accountOptions?: AccountOption[];
  editMode?: boolean;
  editData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  formInline: () => ({
    user_id: "",
    consumption_date: "",
    ad_plan_id: 0,
    input_type: "manual",
    manual_data: [{
      agent_id: "",
      amount: ""
    }],
    account_data: [{
      key: "account_1",
      account_id: "",
      amount: ""
    }]
  }),
  userOptions: () => [],
  agentOptions: () => [],
  accountOptions: () => [],
  editMode: false,
  editData: () => null
});

const ruleFormRef = ref();
// 获取前一天日期作为默认值（一般当天录入前一天数据）
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const defaultDate = yesterday.toISOString().split('T')[0];

// 初始化表单数据
function initFormData() {
  if (props.editMode && props.editData) {
    // 编辑模式，使用传入的数据
    return {
      user_id: props.editData.user_id || "",
      consumption_date: props.editData.consumption_date || defaultDate,
      ad_plan_id: Number(props.editData.ad_plan_id) || 0,
      input_type: props.editData.input_type || "manual",
      manual_data: props.editData.manual_data || [{
        agent_id: "",
        amount: ""
      }],
      account_data: props.editData.account_data || [{
        key: "account_1",
        account_id: "",
        amount: ""
      }]
    };
  } else {
    // 新增模式，使用默认数据
    return {
      user_id: "",
      consumption_date: defaultDate, // 默认选中前一天
      ad_plan_id: 0, // 默认选择计划1
      input_type: "manual",
      manual_data: [{
        agent_id: "",
        amount: ""
      }],
      account_data: [{
        key: "account_1",
        account_id: "",
        amount: ""
      }]
    };
  }
}

const newFormInline = ref(initFormData());

// 错误状态管理
const submitError = ref('');
const submitLoading = ref(false);

// 手工录入添加行
function addManualRow() {
  newFormInline.value.manual_data.push({
    agent_id: "",
    amount: ""
  });
}

// 手工录入删除行
function removeManualRow(index: number) {
  if (newFormInline.value.manual_data.length > 1) {
    newFormInline.value.manual_data.splice(index, 1);
  }
}

// 账号录入添加行
function addAccountRow() {
  const newKey = `account_${Date.now()}`;
  newFormInline.value.account_data.push({
    key: newKey,
    account_id: "",
    amount: ""
  });
}

// 账号录入删除行
function removeAccountRow(index: number) {
  if (newFormInline.value.account_data.length > 1) {
    newFormInline.value.account_data.splice(index, 1);
  }
}

// 获取已选择的代理商ID
function getSelectedAgentIds(currentIndex: number): (number | string)[] {
  return newFormInline.value.manual_data
    .map((item, index) => index !== currentIndex ? item.agent_id : null)
    .filter(id => id && id !== "") // 过滤空值
    .map(id => typeof id === 'string' ? (isNaN(Number(id)) ? id : Number(id)) : id);
}

// 获取已选择的账号ID
function getSelectedAccountIds(currentIndex: number): (number | string)[] {
  return newFormInline.value.account_data
    .map((item, index) => index !== currentIndex ? item.account_id : null)
    .filter(id => id && id !== "") // 过滤空值
    .map(id => typeof id === 'string' ? (isNaN(Number(id)) ? id : Number(id)) : id);
}

// 计算按代理商统计的汇总数据
const summaryByAgent = computed(() => {
  if (newFormInline.value.input_type !== "account") {
    return [];
  }

  const agentSummary = {};

  newFormInline.value.account_data.forEach(item => {
    if (item.account_id && item.amount) {
      const account = availableAccountOptions.value.find(acc => acc.value == item.account_id);
      if (account) {
        const agentId = account.agent_id || account.value; // 使用代理商ID作为key
        const agentName = account.agent_name || "未知代理商";
        const platformText = account.platform_text || "未知平台"; // 直接使用服务端返回的platform_text

        if (!agentSummary[agentId]) {
          agentSummary[agentId] = {
            agent_name: agentName,
            platform: platformText,
            amount: 0
          };
        }
        agentSummary[agentId].amount += parseFloat(item.amount) || 0;
      }
    }
  });

  return Object.values(agentSummary).map((item: any) => ({
    agent_name: item.agent_name,
    platform: item.platform,
    amount: item.amount.toFixed(2)
  }));
});

// 计算总金额
const totalAmount = computed(() => {
  if (newFormInline.value.input_type === "manual") {
    return newFormInline.value.manual_data.reduce((sum, item) => {
      return sum + (parseFloat(item.amount) || 0);
    }, 0);
  } else {
    return newFormInline.value.account_data.reduce((sum, item) => {
      return sum + (parseFloat(item.amount) || 0);
    }, 0);
  }
});

// 计算可用的账号选项（只显示当前选择投放人员创建的账号）
const availableAccountOptions = computed(() => {
  if (newFormInline.value.input_type !== "account" || !newFormInline.value.user_id) {
    return props.accountOptions;
  }

  // 根据 creator_id 筛选出该投放人员创建的账号
  const selectedUserId = Number(newFormInline.value.user_id);
  
  // 从全部账号选项中筛选出该用户创建的账号
  const userCreatedAccounts = props.accountOptions.filter(account => 
    account.creator_id === selectedUserId
  );

  // 编辑模式下仍然返回全部账号选项
  if (props.editMode) {
    return props.accountOptions;
  }

  return userCreatedAccounts;
});

// 计算自动加载提示文本
const autoLoadTip = computed(() => {
  if (props.editMode || newFormInline.value.input_type !== "account") {
    return '';
  }

  if (!newFormInline.value.user_id) {
    return '请先选择投放人员，系统将自动加载其创建的账号';
  }

  const userAccountCount = availableAccountOptions.value.length;

  if (userAccountCount > 1) {
    return `该投放人员共创建了 ${userAccountCount} 个账号，已自动加载，请填写各账号的消耗金额`;
  } else if (userAccountCount === 1) {
    return '该投放人员创建了1个账号，已自动加载，请填写消耗金额';
  } else {
    return '该投放人员暂未创建任何账号';
  }
});

// 自定义合计方法
const getSummaries = (param: { columns: any[], data: any[] }) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 1) {
      sums[index] = '';
      return;
    }
    if (index === 2) {
      const values = data.map((item: any) => Number(item.amount));
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = '$' + sum.toFixed(2);
      } else {
        sums[index] = '$0.00';
      }
      return;
    }
    sums[index] = '';
  });
  return sums;
};

// 监听录入方式变化，重置数据（编辑模式下不执行）
watch(() => newFormInline.value.input_type, (newType) => {
  // 编辑模式下不重置数据
  if (props.editMode) {
    return;
  }

  if (newType === "manual") {
    newFormInline.value.manual_data = [{
      agent_id: "",
      amount: ""
    }];
  } else {
    // 切换到账号录入时，如果已选择投放人员，自动加载其账号
    loadUserAccounts();
  }
});

// 监听投放人员变化
watch(() => newFormInline.value.user_id, () => {
  // 编辑模式下不自动加载
  if (props.editMode) {
    return;
  }

  // 只有在按账号录入模式下才自动加载
  if (newFormInline.value.input_type === "account") {
    loadUserAccounts();
  }
});

// 加载选中投放人员创建的所有账号
function loadUserAccounts() {
  if (!newFormInline.value.user_id || !props.accountOptions) {
    // 没有选择用户或没有账号选项，重置为一行空数据
    newFormInline.value.account_data = [{
      key: `account_${Date.now()}`,
      account_id: "",
      amount: ""
    }];
    return;
  }

  // 获取该投放人员创建的账号
  const selectedUserId = Number(newFormInline.value.user_id);
  const userCreatedAccounts = props.accountOptions.filter(account => 
    account.creator_id === selectedUserId
  );

  if (userCreatedAccounts.length > 0) {
    // 为每个账号创建一行数据
    newFormInline.value.account_data = userCreatedAccounts.map((account, index) => ({
      key: `account_${Date.now()}_${index}`,
      account_id: account.value,
      amount: ""
    }));
    
    const selectedUser = props.userOptions.find(user => user.value === selectedUserId);
    console.log(`已自动为用户 ${selectedUser?.label || '未知'} 加载 ${userCreatedAccounts.length} 个其创建的账号`);
  } else {
    // 该用户没有创建的账号，保持一行空数据
    newFormInline.value.account_data = [{
      key: `account_${Date.now()}`,
      account_id: "",
      amount: ""
    }];
    
    const selectedUser = props.userOptions.find(user => user.value === selectedUserId);
    console.log(`用户 ${selectedUser?.label || '未知'} 没有创建任何账号`);
  }
}

function getRef() {
  return ruleFormRef.value;
}

function getFormData() {
  return newFormInline.value;
}

function clearError() {
  submitError.value = '';
}

function setError(error: string) {
  submitError.value = error;
}

function setLoading(loading: boolean) {
  submitLoading.value = loading;
}

defineExpose({ getRef, getFormData, clearError, setError, setLoading });
</script>

<template>
  <div>
    <!-- 错误提示区域 -->
    <el-alert
      v-if="submitError"
      :title="submitError"
      type="error"
      :closable="true"
      @close="clearError"
      style="margin-bottom: 20px;"
      show-icon
    />

    <el-form
      ref="ruleFormRef"
      :model="newFormInline"
      :rules="batchFormRules"
      label-width="100px"
    >
      <el-row :gutter="30">
        <re-col :span="12">
          <el-form-item label="投放人员" prop="user_id">
            <el-select
              v-model="newFormInline.user_id"
              class="w-full"
              placeholder="请选择投放人员"
              filterable
              clearable
            >
              <el-option
                v-for="option in props.userOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </re-col>

        <re-col v-if="hasPerms(['assets:btn:add_plan_record'])" :span="12">
          <el-form-item label="广告计划" prop="ad_plan_id">
            <el-radio-group v-model="newFormInline.ad_plan_id">
              <el-radio :value="0">计划1</el-radio>
              <el-radio :value="1">计划2</el-radio>
            </el-radio-group>
          </el-form-item>
        </re-col>

        <re-col :span="12">
          <el-form-item label="消耗日期" prop="consumption_date">
            <el-date-picker
              v-model="newFormInline.consumption_date"
              type="date"
              class="w-full"
              placeholder="请选择消耗日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </re-col>

        <re-col :span="24">
          <el-form-item label="录入方式" prop="input_type">
            <el-radio-group v-model="newFormInline.input_type" :disabled="props.editMode">
              <el-radio value="manual">直接录入代理商消耗</el-radio>
              <el-radio value="account">按广告账号录入</el-radio>
            </el-radio-group>

          </el-form-item>
        </re-col>
      </el-row>

      <!-- 手工录入模式 -->
      <div v-if="newFormInline.input_type === 'manual'">
        <el-divider content-position="left">
          <span style="font-size: 14px; color: #666;">代理商消耗录入</span>
          <span style="margin-left: 12px; font-size: 12px; color: #999;">请填写各代理商消耗金额</span>
        </el-divider>

        <el-form-item prop="manual_data">
          <div style="width: 100%;">
            <div
              v-for="(item, index) in newFormInline.manual_data"
              :key="index"
              style="display: flex; align-items: center; margin-bottom: 12px; gap: 12px; padding: 12px; border: 1px solid #e4e7ed; border-radius: 6px; background: #fafafa;"
            >
              <div style="display: flex; align-items: center; gap: 8px; font-size: 14px; color: #666; min-width: 30px;">
                <el-tag size="small" type="info" style="border-radius: 50%;">{{ index + 1 }}</el-tag>
              </div>

              <el-select
                v-model="item.agent_id"
                placeholder="请选择代理商"
                filterable
                clearable
                style="flex: 1; min-width: 200px;"
              >
                <el-option
                  v-for="option in props.agentOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  :disabled="getSelectedAgentIds(index).includes(option.value)"
                />
              </el-select>

              <el-input
                v-model="item.amount"
                placeholder="消耗金额"
                style="width: 150px;"
              >
                <template #suffix>
                  <span style="color: #999;">$</span>
                </template>
              </el-input>

              <el-button
                v-if="newFormInline.manual_data.length > 1"
                type="danger"
                size="small"
                circle
                @click="removeManualRow(index)"
                :icon="Delete"
              />

              <div v-else style="min-width: 32px;"></div>
            </div>

            <el-button
              type="primary"
              plain
              @click="addManualRow"
              style="width: 100%; margin-top: 8px;"
            >
              添加一行
            </el-button>
          </div>
        </el-form-item>
      </div>

      <!-- 按账号录入模式 -->
      <div v-if="newFormInline.input_type === 'account'">
        <el-divider content-position="left">
          <span style="font-size: 14px; color: #666;">账号消耗录入</span>
          <span style="margin-left: 12px; font-size: 12px; color: #999;">请填写账号消耗情况，系统将自动汇总代理商消耗总数</span>
        </el-divider>

        <!-- 自动加载提示 -->
        <div v-if="autoLoadTip" style="margin-bottom: 16px;">
          <el-alert
            :title="autoLoadTip"
            type="info"
            :closable="false"
            show-icon
            style="border-left: 4px solid #409eff;"
          />
        </div>

        <el-form-item prop="account_data">
          <div style="width: 100%;">
            <div
              v-for="(account, index) in newFormInline.account_data"
              :key="account.key"
              style="display: flex; align-items: center; margin-bottom: 12px; gap: 12px; padding: 12px; border: 1px solid #e4e7ed; border-radius: 6px; background: #fafafa;"
            >
              <div style="display: flex; align-items: center; gap: 8px; font-size: 14px; color: #666; min-width: 30px;">
                <el-tag size="small" type="info" style="border-radius: 50%;">{{ index + 1 }}</el-tag>
              </div>

              <el-select
                v-model="account.account_id"
                placeholder="请选择广告账号"
                filterable
                clearable
                style="flex: 1; min-width: 200px;"
              >
                <el-option
                  v-for="option in availableAccountOptions"
                  :key="option.value"
                  :label="`${option.label} (${option.agent_name})`"
                  :value="option.value"
                  :disabled="getSelectedAccountIds(index).includes(option.value)"
                />
              </el-select>

              <el-input
                v-model="account.amount"
                placeholder="消耗金额"
                style="width: 150px;"
              >
                <template #suffix>
                  <span style="color: #999;">$</span>
                </template>
              </el-input>

              <el-button
                v-if="newFormInline.account_data.length > 1"
                type="danger"
                size="small"
                circle
                @click="removeAccountRow(index)"
                :icon="Delete"
              />

              <div v-else style="min-width: 32px;"></div>
            </div>

            <el-button
              type="primary"
              plain
              @click="addAccountRow"
              style="width: 100%; margin-top: 8px;"
            >
              添加一行
            </el-button>
          </div>
        </el-form-item>

        <!-- 按代理商汇总 -->
        <div v-if="summaryByAgent.length > 0" style="margin-top: 20px;">
          <el-divider content-position="left">
            <span style="font-size: 14px; color: #666;">汇总数据</span>
          </el-divider>

          <el-table :data="summaryByAgent" size="small" border style="width: 100%;" show-summary :summary-method="getSummaries">
            <el-table-column prop="agent_name" label="代理商" width="200" align="center" />
            <el-table-column prop="platform" label="平台" width="120" align="center" />
            <el-table-column prop="amount" label="消耗金额($)" align="right" />
          </el-table>
        </div>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.w-full {
  width: 100%;
}
</style>
